import Cookies from 'js-cookie'

const TOKEN_KEY = 'admin_token'
const REFRESH_TOKEN_KEY = 'admin_refresh_token'

// Token相关操作
export function getToken(): string | undefined {
  return Cookies.get(TOKEN_KEY)
}

export function setToken(token: string): void {
  Cookies.set(TOKEN_KEY, token, { expires: 7 }) // 7天过期
}

export function removeToken(): void {
  Cookies.remove(TOKEN_KEY)
  Cookies.remove(REFRESH_TOKEN_KEY)
}

// Refresh Token操作
export function getRefreshToken(): string | undefined {
  return Cookies.get(REFRESH_TOKEN_KEY)
}

export function setRefreshToken(refreshToken: string): void {
  Cookies.set(REFRESH_TOKEN_KEY, refreshToken, { expires: 30 }) // 30天过期
}

// 检查Token是否过期
export function isTokenExpired(token?: string): boolean {
  if (!token) {
    token = getToken()
  }
  
  if (!token) {
    return true
  }
  
  try {
    // 解析JWT token的payload部分
    const payload = JSON.parse(atob(token.split('.')[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    
    // 检查是否过期（提前5分钟判断为过期）
    return payload.exp < currentTime + 300
  } catch (error) {
    console.error('Token解析失败:', error)
    return true
  }
}

// 权限检查
export function hasPermission(permission: string, userPermissions: string[] = []): boolean {
  if (userPermissions.includes('*')) {
    return true // 超级管理员权限
  }
  
  return userPermissions.includes(permission)
}

export function hasRole(role: string, userRoles: string[] = []): boolean {
  return userRoles.includes(role)
}

// 权限指令辅助函数
export function checkPermissions(permissions: string | string[], userPermissions: string[] = []): boolean {
  if (typeof permissions === 'string') {
    return hasPermission(permissions, userPermissions)
  }
  
  if (Array.isArray(permissions)) {
    return permissions.some(permission => hasPermission(permission, userPermissions))
  }
  
  return false
}